<?
/*********************** INCLUDES *********************************************/
  $includePath=realpath(dirname(__FILE__)."/../");
  require_once($includePath.'/config/cfg.php');
  //require($includePath.'/constants.php');
  require_once ($includePath.'/lib/phpagi/phpagi.php');
  //require($includePath.'/agi/agifunction.php');

/*********************** INITIALIZATION ***************************************/

  $agi = new AGI();
  // Extract rule context
  $extension = $agi->request["agi_extension"];
  $ruleContext = $agi->request["agi_context"];
  $res=$db->Execute("SELECT id FROM cw_rule WHERE name='$ruleContext'");
  $arr=$res->FetchRow();
  $ruleSetId=$arr["id"];
  // Get AGI parameters 
  // (WARNING: GET array may be null in many cases, parseArgv take $_SERVER content) 
  parse_str($_SERVER["argv"][1], $var_GET);
  $entityId=$var_GET["entity"];    
  $entityGroup=$var_GET["group"];  
  $entityExt=str_replace(".","",str_replace("_","",$var_GET["extension"]));
  // Get Mandatory Channel
  $mandatoryChannel=$agi->get_variable("MANDATORYCHANNEL");
  $mandatoryChannel=$mandatoryChannel["data"];
   
  agiError("-----------------------------------------------");
  agiError("Outgoing Rule Set: [$ruleSetId]$ruleContext (ext:$extension - grp: $entityGroup - entId: $entityId)");
  agiError("-----------------------------------------------");
/*********************** PAGE LOGIC ********************************************/
  
  // DIAL SOMETHING
  $canContinue=true;
  $qry="SELECT * FROM cw_rule_outgoing WHERE rule=$ruleSetId ORDER BY priority";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) {
    $id=$arr["id"];
    $rule=$arr["rule"];
    $priority=$arr["priority"];
    $timesegment=$arr["timesegment"];
    $group=$arr["group"];
    $entity=$arr["entity"];
    $resource=$arr["resource"];
    $provider=$arr["provider"];
    $action=$arr["action"];
    if ($resource!="0") {
      $channel=_getTrunk($resource);
      $channelArr=split("&",$channel);
    }else $channelArr=array();
    agiError("Rule: $id (entity: $entity, group: $group)");
    
    // if mandatory channel is setted dial $extension as a phone number
    if ($mandatoryChannel!=""){ 
        $entityGroup=GROUP_OF_PHONENUMBER;
        $entityId="";
      }
      
    // check if some rule are triggered
    if(checkTime($timesegment)===false) continue;
    if  (
          ( 
            // if the rule match *
            ($group==GROUP_OF_ALL) or
            // if the rule (entity) refer to the extension's entity 
            ($entity==$entityId) or 
            // if the rule (group) refer to the extension's entity 
            (is_array(_getGroup($entityId)) AND in_array($group,_getGroup($entityId))) or
            // if the rule (entity) refer to the extension's group
            ($entityId=="" AND is_array(_getGroup($entity)) AND in_array($entityGroup,_getGroup($entity))) or 
            // if the rule (group) refer to the extension's group (happen only when rule match a GROUP_OF_NUMBERS)
            ($entityId=="" AND $entityGroup==_metaGroupFromGroup($group)) or
            // if the rule (group) refer to the extension's group 
            ($entityId=="" AND $entityGroup==$group)
          )
          AND
          ( 
            $canContinue===true
          )  
        ) 
      {
      agiError("  TRIGGERED RULE $id!");
      switch ($entityGroup) {
        case GROUP_OF_EXTENSION:
          agiError("  This is an extension: $entityExt");
          if ($action==RULE_ALLOW) {
            agiError("  ALLOWED");
            $techName=_extractTech($entityId);
            $channelName=$techName."/".$extension;
            agiError("  ----------------> macro stdexten|$extension|$channelName");
            //$agi->exec("macro stdexten|$extension|$channelName");
            $agi->exec("macro stdexten|$channelName");
            $canContinue=false;
          }
          if ($action==RULE_DENY) {
            agiError("  DENIED!");
            //$agi->text2wav ("You don't have the permission to call this extension");
            $agi->exec("Congestion");
            $canContinue=false;
          } 
        break;
        case GROUP_OF_PHONENUMBER:
          agiError("  This is a phone number: $entityExt");
          $included = _isIncluded($extension,$entity,$group);
          // RULE_ALLOW
          if (($action==RULE_ALLOW)&&($included===true)) {
            if (in_array($mandatoryChannel,$channelArr) or $resource=="0" or $mandatoryChannel=="") {
              // check previous DENY rules
              $prev_denied["all"]=false;
              $prev_denied["list"]="";
              if($mandatoryChannel=="") // if $mandatoryChannel isn't setted --> dialout
                $prevDenied=_isPrevDenied($extension,$ruleSetId,$priority);
              // set channel and dialout
              if($prevDenied["all"]===true) $canContinue=true;
              else {
                if ($resource!="0" and $mandatoryChannel=="") {
                  $channel=_getDiffChannel($channel,$prevDenied["list"]);
                  if($channel!=""){
                    $agi->set_variable("TRUNK", $channel); 
                    agiError("  ALLOWED on Trunks: $channel");
                  } else {
                    agiError("  DENIED! (allowed trunks has been previously denied)");
                    $agi->exec("Congestion");
                    $canContinue=false;
                    break;
                  }     
                } else if ($mandatoryChannel!="") {
                  $agi->set_variable("TRUNK", $mandatoryChannel);
                  agiError("  ALLOWED: set Trunk to the mandatory $mandatoryChannel");
                } else {
                  $allTrunks=$agi->get_variable("TRUNK");
                  $allTrunks=$allTrunks["data"];
                  $channel=_getDiffChannel($allTrunks,$prevDenied["list"]); 
                  if($channel!=""){
                    $agi->set_variable("TRUNK", $channel);
                    agiError("  ALLOWED on Trunks: $channel");
                  } else {
                    agiError("  DENIED! (allowed trunks has been previously denied)");
                    $agi->exec("Congestion");
                    $canContinue=false;
                    break;
                  }
                }              
                $extension=substr($extension,strlen($outgoing_prefix));
                agiError("  ----------------> macro dialout|$extension");
                //$agi->text2wav ("You are calling the number $extension");
                $agi->exec("macro dialout|$extension");
                $canContinue=false;
              }
            } 
            else {
              $canContinue=true;
              agiError("  SKIPPED (allowed trunk list doesn't contain mandatory trunk)");
            }
          }
          // RULE_DENY
          else if(($action==RULE_DENY)&&($included===true)) {
            if(  
                ($mandatoryChannel!="" and (in_array($mandatoryChannel,$channelArr) or $resource=="0"))
                or 
                ($mandatoryChannel=="" and $resource=="0")  
              ){
              agiError("  DENIED!");
              $agi->exec("Congestion");
              $canContinue=false;
            }else{
              $canContinue=true;
              if($mandatoryChannel=="") agiError("  SKIPPED (rule denies one or more trunks but not all)");
              else agiError("  SKIPPED (rule denies one or more trunks but not mandatory trunk)");
            }
          }
          // not included
          else {
            $canContinue=true;
            agiError("  SKIPPED (extension matches no pattern)");
          }
        break;
        case GROUP_OF_RESOURCE:
          agiError("  This is a resource: $entityExt");
          if ($action==RULE_ALLOW) {
            $qry="SELECT * FROM cw_channel WHERE `id`=".$entityId;
            $resT=$db->Execute($qry);
            $arrT=$resT->FetchRow();
            $agi->set_variable("MANDATORYCHANNEL", $arrT["name"]);
            agiError("  ALLOWED (set MandatoryChannel to ".$arrT["name"].")");
            $newExtension=substr($extension,strlen($entityExt));
            $agi->goto($ruleContext,$newExtension,1); 
            $canContinue=false;
          }
          if ($action==RULE_DENY) {
            agiError("  DENIED!");
            $agi->exec("Congestion");
            $canContinue=false;
          }
        break;
        case GROUP_OF_APPLICATION:
          agiError("  This is an Application: $entityExt");
          if ($action==RULE_ALLOW) {
            agiError("  ALLOWED ");
            $qry="SELECT * FROM cw_application WHERE id=".$entityId;
            $resA=$db->Execute($qry);
            $arrA=$resA->FetchRow();

            if ($arrA["code"]!="") {
              $lineArr=split("\n",$arrA["code"]);
              if (is_array($lineArr)) foreach($lineArr as $line) {
                agiError("  Executing code: $line");
                $agi->exec($line);
              }
            }
            if ($arrA["macro"]!="") {
              $arrMacro=prepareMacro($arrA["macro"],$arrA["parameter"]);
              agiError("  Executing macro ".$arrMacro[0].$arrMacro[1]." ...");
              $agi->exec("macro ".$arrMacro[0].$arrMacro[1]);
            }
            $canContinue=false;
          }
          if ($action==RULE_DENY) {
            agiError("  DENIED!");
            $agi->exec("Congestion");
            $canContinue=false;
          }
        break;
        case GROUP_OF_OFFICE:
          agiError("  This is an office: $entityExt");
          if ($action==RULE_ALLOW) {
            $qry="SELECT * FROM cw_channel WHERE `key`=".$entityId;
            $resT=$db->Execute($qry);
            $arrT=$resT->FetchRow();
            $agi->set_variable("TRUNK", $arrT["name"]);
            agiError("set TRUNK: ".$arrT["name"]);              
            agiError("  ----------------> macro dialout|$destination");
            $agi->exec("macro dialout|s");
            $canContinue=false;
          }
          if ($action==RULE_DENY) {
            agiError("  DENIED!");
            $agi->exec("Congestion");
            $canContinue=false;
          }
        break;
        default:
          agiError("  This is an Unknown entity");
        break;
      }
    } 
      
  }
  agiError("Exit from dial.php\n");
    

?>
